/*
 *  Copyright (c)  2016-NOW  Jacars Co.Ltd.
 *  All rights reserved.
 */
package com.jacars.biz.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.jacars.biz.user.dao.model.JsptDept;
import com.jacars.biz.user.dao.service.JsptDeptService;
import com.jacars.biz.user.service.DeptService;
import com.jacars.biz.user.vo.JsptDeptVO;
import com.jacars.common.annotation.LoginUser;
import com.jacars.common.api.PageResult;
import com.jacars.common.api.Result;
import com.jacars.common.constant.CommonConstant;
import com.jacars.common.model.JsptUser;
import com.jacars.common.utils.BeanUtil;
import com.jacars.common.utils.FuncUtil;
import com.jacars.common.utils.node.ForestNodeMerger;
import com.jacars.common.utils.node.INode;
import com.jacars.db.support.Condition;
import com.jacars.db.support.Query;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 控制器
 *
 * @author Chill
 */
@RestController
@AllArgsConstructor
@RequestMapping("/dept")
@Api(value = "部门", tags = "部门")
public class DeptController {

	private DeptService deptService;

	private JsptDeptService jsptDeptService;

	/**
	 * 分页数据
	 * @param jsptDept
	 * @param query
	 * @param jsptUser
	 * @return
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "列表", notes = "传入dept")
	public PageResult<INode> page(JsptDept jsptDept, Query query, @LoginUser(isFull = true) JsptUser jsptUser) {
		QueryWrapper<JsptDept> queryWrapper = Condition.getQueryWrapper(jsptDept);
		IPage<JsptDept> page = jsptDeptService.page(Condition.getPage(query),
				(!jsptUser.getTenantId().equals(CommonConstant.ADMIN_TENANT_ID))
						? queryWrapper.lambda().eq(JsptDept::getTenantId, jsptUser.getTenantId())
						: queryWrapper);
		List<JsptDept> list = page.getRecords();
		List<INode> collect = list.stream().map(k -> BeanUtil.copy(k, JsptDeptVO.class)).collect(Collectors.toList());
		List<INode> iNodeList =  ForestNodeMerger.merge(collect);

		return PageResult.succeed(iNodeList, page.getTotal());
	}

	/**
	 * 列表数据
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "列表", notes = "传入dept")
	public Result<List<INode>> list(@ApiIgnore @RequestParam Map<String, Object> dept, @LoginUser(isFull = true) JsptUser jsptUser) {
		QueryWrapper<JsptDept> queryWrapper = Condition.getQueryWrapper(dept, JsptDept.class);
		List<JsptDept> list = jsptDeptService.list(
				(!jsptUser.getTenantId().equals(CommonConstant.ADMIN_TENANT_ID))
						? queryWrapper.lambda().eq(JsptDept::getTenantId, jsptUser.getTenantId())
						: queryWrapper);
		List<INode> collect = list.stream().map(dept1 -> BeanUtil.copy(dept1, JsptDeptVO.class)).collect(Collectors.toList());
		List<INode> iNodeList =  ForestNodeMerger.merge(collect);

		return Result.succeed(iNodeList);
	}

	/**
	 * 获取部门树形结构
	 *
	 * @return
	 */
	@GetMapping("/tree")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "树形结构", notes = "树形结构")
	public Result<List<JsptDeptVO>> tree(String tenantId, @LoginUser(isFull = true) JsptUser jsptUser) {
		List<JsptDeptVO> tree = deptService.tree(FuncUtil.toStr(tenantId, jsptUser.getTenantId()));
		return Result.succeed(tree);
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/create")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入dept")
	public Result submit(@RequestBody JsptDept jsptDept) {
		// 自动注入了tenantid
		jsptDept.setTenantId(null);
		jsptDeptService.save(jsptDept);
		return Result.succeed("操作成功");
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入dept")
	public Result update(@RequestBody JsptDept jsptDept) {
		// 自动注入了tenantid
		jsptDept.setTenantId(null);
		if (jsptDept.getParentId() == null) {
			jsptDept.setParentId(0L);
		}
		jsptDeptService.updateById(jsptDept);
		return Result.succeed("操作成功");
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "删除", notes = "传入ids")
	public Result remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		jsptDeptService.removeByIds(FuncUtil.toLongList(ids));
		return Result.succeed("操作成功");
	}

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入dept")
	public Result<JsptDeptVO> detail(JsptDept jsptDept) {
		JsptDept detail = jsptDeptService.getOne(Condition.getQueryWrapper(jsptDept));
		//如果查询不到detail，需要特殊处理，因为此时无法转换成JsptDeptVo
		JsptDeptVO deptVO = new JsptDeptVO();
		if (FuncUtil.notNull(detail)) {
			deptVO = BeanUtil.copy(detail, JsptDeptVO.class);
			if (FuncUtil.equals(detail.getParentId(), CommonConstant.TOP_PARENT_ID)) {
				deptVO.setParentName(CommonConstant.TOP_PARENT_NAME);
			} else {
				JsptDept parent = jsptDeptService.getById(detail.getParentId());
				deptVO.setParentName(parent.getDeptName());
			}
		}

		return Result.succeed(deptVO);
	}


	/**
	 * 模糊查询部门，根据部门名称名左右匹配
	 *
	 * @param deptName
	 */
	@GetMapping(value = "/fuzzy")
	public PageResult<JsptDept> fuzz(@RequestParam(name = "deptName", required = false) String deptName) {
		List<JsptDept> list = null;
		if (FuncUtil.equals("", deptName) || FuncUtil.isNull(deptName)) {
			// 查询全部
			list = jsptDeptService.list();
		} else {
			// 模糊查询
			list = jsptDeptService.list(Wrappers.<JsptDept>lambdaQuery().like(JsptDept::getDeptName, deptName));

		}

		return PageResult.succeed(list);
	}
}
